package cn.heyige.backend.controller;

import cn.heyige.backend.algorithm.AccuracyAnalyzer;
import cn.heyige.backend.common.CommResponse;
import cn.heyige.backend.dto.DivinationFeedbackDTO;
import cn.heyige.backend.entity.DivinationFeedbackDO;
import cn.heyige.backend.entity.UserDO;
import cn.heyige.backend.exception.BusinessException;
import cn.heyige.backend.exception.ErrorCode;
import cn.heyige.backend.service.FeedbackService;
import cn.heyige.backend.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("api/feedback")
@Slf4j
@Tag(name = "占卜反馈接口", description = "用户对占卜结果的反馈管理和准确性分析")
@RequiredArgsConstructor
public class FeedbackController {
    
    private final FeedbackService feedbackService;
    private final UserService  userService;
    private final AccuracyAnalyzer accuracyAnalyzer;

    
    @PostMapping
    @Operation(summary = "提交反馈", description = "用户提交对占卜结果的反馈")
    public CommResponse<DivinationFeedbackDTO> submitFeedback(@RequestBody DivinationFeedbackDTO feedbackDTO) {
        try {
            // 验证用户存在
            UserDO user = Optional.ofNullable(userService.getById(feedbackDTO.getUserId()))
                    .orElseThrow(() -> new BusinessException(ErrorCode.USER_NOT_FOUND));
            
            // 创建反馈实体
            DivinationFeedbackDO feedback = new DivinationFeedbackDO();
            feedback.setUserId(feedbackDTO.getUserId());
            feedback.setDivinationType(feedbackDTO.getDivinationType());
            feedback.setOriginalHexagram(feedbackDTO.getOriginalHexagram());
            feedback.setChangedHexagram(feedbackDTO.getChangedHexagram());
            feedback.setIsAccurate(feedbackDTO.getIsAccurate());
            feedback.setFeedbackComment(feedbackDTO.getFeedbackComment());
            feedback.setUserCity(user.getCurrentCity());
            feedback.setUserMood(user.getMoodStatus());
            
            // 保存反馈
            DivinationFeedbackDO savedFeedback = feedbackService.saveFeedback(feedback);
            
            // 转换为DTO返回
            DivinationFeedbackDTO savedDTO = new DivinationFeedbackDTO();
            savedDTO.setId(savedFeedback.getId());
            savedDTO.setUserId(savedFeedback.getUserId());
            savedDTO.setDivinationType(savedFeedback.getDivinationType());
            savedDTO.setOriginalHexagram(savedFeedback.getOriginalHexagram());
            savedDTO.setChangedHexagram(savedFeedback.getChangedHexagram());
            savedDTO.setIsAccurate(savedFeedback.getIsAccurate());
            savedDTO.setFeedbackComment(savedFeedback.getFeedbackComment());
            savedDTO.setUserCity(savedFeedback.getUserCity());
            savedDTO.setUserMood(savedFeedback.getUserMood());
            savedDTO.setCreateTime(savedFeedback.getCreateTime());
            
            return CommResponse.ok(savedDTO);
        } catch (Exception e) {
            log.error("提交反馈失败", e);
            return CommResponse.fail(400, e.getMessage());
        }
    }
    
    @GetMapping("/user/{userId}")
    @Operation(summary = "获取用户反馈历史", description = "获取指定用户的反馈历史")
    public CommResponse<List<DivinationFeedbackDTO>> getUserFeedback(@PathVariable Integer userId) {
        try {
            List<DivinationFeedbackDTO> feedbacks = feedbackService.getFeedbackByUserId(userId);
            return CommResponse.ok(feedbacks);
        } catch (Exception e) {
            log.error("获取用户反馈历史失败", e);
            return CommResponse.fail(400, e.getMessage());
        }
    }
    
    @GetMapping("/stats/hexagram")
    @Operation(summary = "获取卦象准确率统计", description = "获取各卦象的准确率统计")
    public CommResponse<Map<String, Double>> getHexagramAccuracyRates() {
        try {
            Map<String, Double> accuracyRates = feedbackService.getHexagramAccuracyRates();
            return CommResponse.ok(accuracyRates);
        } catch (Exception e) {
            log.error("获取卦象准确率统计失败", e);
            return CommResponse.fail(400, e.getMessage());
        }
    }
    
    @GetMapping("/stats/city")
    @Operation(summary = "获取城市准确率统计", description = "获取各城市的准确率统计")
    public CommResponse<Map<String, Double>> getCityAccuracyRates() {
        try {
            Map<String, Double> accuracyRates = feedbackService.getCityAccuracyRates();
            return CommResponse.ok(accuracyRates);
        } catch (Exception e) {
            log.error("获取城市准确率统计失败", e);
            return CommResponse.fail(400, e.getMessage());
        }
    }
    
    @GetMapping("/stats/mood")
    @Operation(summary = "获取心情准确率统计", description = "获取各心情状态的准确率统计")
    public CommResponse<Map<String, Double>> getMoodAccuracyRates() {
        try {
            Map<String, Double> accuracyRates = feedbackService.getMoodAccuracyRates();
            return CommResponse.ok(accuracyRates);
        } catch (Exception e) {
            log.error("获取心情准确率统计失败", e);
            return CommResponse.fail(400, e.getMessage());
        }
    }
    
    @PostMapping("/analyze")
    @Operation(summary = "手动触发反馈分析", description = "手动触发反馈数据分析和权重更新")
    public CommResponse<String> triggerAnalysis() {
        try {
            feedbackService.analyzeAndUpdateWeights();
            return CommResponse.ok("反馈数据分析和权重更新已完成");
        } catch (Exception e) {
            log.error("触发反馈分析失败", e);
            return CommResponse.fail(400, e.getMessage());
        }
    }
    
    @GetMapping("/analysis/city-hexagram")
    @Operation(summary = "获取城市卦象准确率分析", description = "分析不同城市对不同卦象的准确率")
    public CommResponse<Map<String, Map<String, Double>>> getCityHexagramAccuracyAnalysis() {
        try {
            Map<String, Map<String, Double>> analysis = accuracyAnalyzer.analyzeCityHexagramAccuracy();
            return CommResponse.ok(analysis);
        } catch (Exception e) {
            log.error("获取城市卦象准确率分析失败", e);
            return CommResponse.fail(400, e.getMessage());
        }
    }
    
    @GetMapping("/analysis/mood-hexagram")
    @Operation(summary = "获取心情卦象准确率分析", description = "分析不同心情对不同卦象的准确率")
    public CommResponse<Map<String, Map<String, Double>>> getMoodHexagramAccuracyAnalysis() {
        try {
            Map<String, Map<String, Double>> analysis = accuracyAnalyzer.analyzeMoodHexagramAccuracy();
            return CommResponse.ok(analysis);
        } catch (Exception e) {
            log.error("获取心情卦象准确率分析失败", e);
            return CommResponse.fail(400, e.getMessage());
        }
    }
    
    @PostMapping("/analysis/clear-cache")
    @Operation(summary = "清除分析缓存", description = "清除占卜准确性分析缓存")
    public CommResponse<String> clearAnalysisCache() {
        try {
            accuracyAnalyzer.clearAnalysisCache();
            return CommResponse.ok("分析缓存已清除");
        } catch (Exception e) {
            log.error("清除分析缓存失败", e);
            return CommResponse.fail(400, e.getMessage());
        }
    }
}
